'use strict'

var isDebugMode = false;
var resourcePath = "";


function setResourcePath(path) {
    resourcePath = path;
}

function ClientEvent(type, name, action) {
    this.type = type;
    this.name = name;
    this.action = action;
}


/*********************************************************************************
 VARIABLES*/

var ship = {active: false};
var playersList = {};
var gamer = {
    name: undefined,
    stars: undefined,
    cards: [],
    in_duel: false
};

var sockJS;
var stompClient;
var sendAnswer;


function makeAnswer(playersName) {
    sendAnswer('{"type":"PLAYER","name":"' + playersName + '","action":"challenge.add"}')
}

function selectCard(cardName, tableId) {
    sendAnswer('{"type":"TABLE","name":"' + tableId + '","action":"' + cardName + '"}')
}


/*********************************************************************************
 DTO SHIP*/

function processDtoShip(dtoObject) {

    console.log("========= processDtoShip");


    //KOSTYL
    if (dtoObject.state === "SELECTING") {
        ship.active = false;
        //timerSetTime(dtoObject.time);
    }
    else {
        //if(ship.active === false) {timerStart();}
        timerStop();
        timerSetTime(dtoObject.time);
        timerStart();
        ship.active = true;
    }


    //$("h1#timer").html("Game finishes in" + dtoObject.time);
    //$("h1#leftCards").html("Cards Left = Paper:" + dtoObject.deck.Paper + " Scissors:" + dtoObject.deck.Scissors + " Stone:" + dtoObject.deck.Stone);
    $("#leftStone").html(dtoObject.deck.STONE);
    $("#leftScissors").html(dtoObject.deck.SCISSORS);
    $("#leftPaper").html(dtoObject.deck.PAPER);


    //Filling/updating list of players
    for (var i in dtoObject.players) {
        var elem = dtoObject.players[i];
        if (playersList[elem.name] === undefined) {
            playersList[elem.name] = {"state": elem.state, "stars": elem.stars};
            //TODO Draw changes on UI
        } else {
            if (!elem.delet) {
                playersList[elem.name].state = elem.state;
                playersList[elem.name].stars = elem.stars;
            } else {
                //TODO clear that player from UI
                delete playersList[elem.name];
            }
        }
    }
    drawPlayerList();
}


/*********************************************************************************
 DRAW METHODS*/


function drawPlayerList() {

    console.log("-------------drawPlayerList");
    var buttonString = '', starsString = '', name;
    $(".playersInRoom table.playerState").remove();
    for (var p in playersList) {
        var elem = playersList[p];
        buttonString = starsString = name = '';

        //adjust Duel button appearance
        if (elem.challenged === true) {
            buttonString = '<button class="duelBtn challenged" name="' + p + '" onclick="makeAnswer(this.name);">Duel</button>';
        } else if (elem.challenging === true) {
            buttonString = '<button class="duelBtn challenging" name="' + p + '" onclick="makeAnswer(this.name);">Duel</button>';
        } else {
            buttonString = '<button class="duelBtn" name="' + p + '" onclick="makeAnswer(this.name);">Duel</button>';
        }

        //Set quantity of stars appearance
        for (var i = 0; i < elem.stars; i++) {
            starsString += '<img src="' + resourcePath + '/resources/img/room_page/playersStar.png">';
        }
        ;

        // if player is the gamer - dont draw it
        if (p !== gamer.name) {
            $(".playersInRoom").append('<table class="playerState" id="' + p + '">\
                                          <tr>\
                                            <td>\
                                                <table class="playerStars">\
                                                    <tr>\
                                                    <!-- here to be stars -->' +
            starsString +
            '</tr>\
        </table>\
    </td>\
    <td ROWSPAN=2>' + buttonString + '</td>\
                                          </tr>\
                                          <tr>\
                                            <td style="font-size: 14px;font-weight: bold"><span id="playerName">' + p + ' ' + elem.state + '</span></td>\
                                          </tr>\
                                       </table>');

        }
    }
    // If ship.state === SELECTING - hide buttons -- Kostyl
    if (ship.active === false) {
        $(".duelBtn").css("visibility", "hidden");
    }
    else {
        $(".duelBtn").css("visibility", "visible");
    }
}


function drawGamerRes() {

    console.log("-------------drawGamerRes");
    var cardsString = '';
    $(".playerCardsStars #cardPanel").empty();
    $("p#gamerName").html(gamer.name + ' have:');
    $("#starCounter").html(gamer.stars);
    for (var i in gamer.cards) {
        for (var j in gamer.cards[i]) {
            $(".playerCardsStars #cardPanel").append('<td><img src="' + resourcePath + '/resources/img/room_page/' + j.toLowerCase() + '.png"></td>').append('<td>' + gamer.cards[i][j] + '</td>');
        }
    }
}


function drawGamerResOnDuel(argument) {
    console.log("-------------drawGamerResOnDuel");
    var cardsString = '';
    $("#duelCardPanel").empty();
    $("#duelStarCounter").html(gamer.stars);
    console.log(gamer.cards);
    for (var i in gamer.cards) {
        for (var j in gamer.cards[i]) {
            $("#duelCardPanel").append('<tr><td><img src="' + resourcePath + '/resources/img/room_page/' + j.toLowerCase() + '.png" onclick="selectCard(' + "'" + j + "'" + ',' + gamer.tableId + ')"></td><td>' + gamer.cards[i][j] + '</td></tr>');
        }
    }
}

function drawEnemyStarsOnDuel(argument) {
    console.log("-------------drawEnemyStarsOnDuel");
    $("#duelEnemyStarCounter").html(playersList[gamer.enemyName].stars);
    $("#enemyName").html(gamer.enemyName);
}


/*********************************************************************************
 DTO PLAYER*/

function processDtoPlayer(dtoObject) {
    console.log("========= processDtoPlayer");
    gamer.name = dtoObject.name;
    gamer.stars = playersList[gamer.name].stars;
    var counter = 0;
    for (var cardName in dtoObject.deck) {
        gamer.cards[counter] = {};
        gamer.cards[counter][cardName] = dtoObject.deck[cardName];
        counter++;
    }

// Update set of challanging players
    for (var u in dtoObject.whoChallenging) {
        var elem = dtoObject.whoChallenging[u];
        if (playersList[elem.name] !== undefined) {
            if (elem.delet) {
                playersList[elem.name].challenging = false;
            } else {
                playersList[elem.name].challenging = true;
            }
        }
    }

// Update set of challanged players
    for (var y in dtoObject.iChallenged) {
        var elem = dtoObject.iChallenged[y];
        if (playersList[elem.name] !== undefined) {
            if (elem.delet) {
                playersList[elem.name].challenged = false;
            } else {
                playersList[elem.name].challenged = true;
            }
        }
    }

    drawGamerRes();
    drawPlayerList();
}


/*********************************************************************************
 DTO TABLE*/




function processDtoTable(dtoObject) {
    console.log("========= processDtoTable");
    console.log(dtoObject);

    if (dtoObject.state === "EMPTY") {

        if (gamer.tableId === dtoObject.id) {
            gamer.in_duel = false;

            close_duel();
            gamer.tableId = -1;
        }

        $("#desks #table" + dtoObject.id + " .leftSide").empty();
        $("#desks #table" + dtoObject.id + " .leftSideCard").empty();
        $("#desks #table" + dtoObject.id + " .rightSide").empty();
        $("#desks #table" + dtoObject.id + " .rightSideCard").empty();


        return;
    }

    if (dtoObject.left.name === gamer.name || dtoObject.right.name === gamer.name) {
        console.log("********************* YOUR GAME***************************");

        gamer.tableId = dtoObject.id;

        //TODO
        if (dtoObject.left.name === gamer.name) {
            gamer.side = "left";
            gamer.enemyName = dtoObject.right.name;
        }

        if (dtoObject.right.name === gamer.name) {
            gamer.side = "right";
            gamer.enemyName = dtoObject.left.name;
        }

        playersList[gamer.enemyName].challenging = false;
        playersList[gamer.enemyName].challenged = false;
        if (gamer.in_duel === false) {

            gamer.in_duel = true;
            //Show LightBox
            open_duel();
            drawGamerResOnDuel();
            //draw my panel
            drawEnemyStarsOnDuel();
            //draw opponent panel

        }


        if (dtoObject.left.card === null) {
            if (gamer.side === "left") {
                $("#mySideCardPlace").empty();
            } else {
                $("#enemySideCardPlace").empty();
            }
        } else {
            if (gamer.side === "left") {
                $("#mySideCardPlace").html('<img src="' + resourcePath + '/resources/img/duel_page/' + dtoObject.left.card.toLowerCase() + '2.gif">');
            } else {
                $("#enemySideCardPlace").html('<img src="' + resourcePath + '/resources/img/duel_page/' + dtoObject.left.card.toLowerCase() + '2.gif">');
            }
        }

        if (dtoObject.right.card === null) {
            if (gamer.side === "right") {
                $("#mySideCardPlace").empty();
            } else {
                $("#enemySideCardPlace").empty();
            }
        } else {
            if (gamer.side === "right") {
                $("#mySideCardPlace").html('<img src="' + resourcePath + '/resources/img/duel_page/' + dtoObject.right.card.toLowerCase() + '2.gif">');
            } else {
                $("#enemySideCardPlace").html('<img src="' + resourcePath + '/resources/img/duel_page/' + dtoObject.right.card.toLowerCase() + '2.gif">');
            }
        }


    }

    $("#desks #table" + dtoObject.id + " .leftSide").html(dtoObject.left.name);
    if(dtoObject.left.card !== null){
        $("#desks #table" + dtoObject.id + " .leftSideCard").html('<img src="' + resourcePath + '/resources/img/room_page/' + dtoObject.left.card.toLowerCase() + '.png">');
    }
    $("#desks #table" + dtoObject.id + " .rightSide").html(dtoObject.right.name);
    if(dtoObject.right.card !== null){
        $("#desks #table" + dtoObject.id + " .rightSideCard").html('<img src="' + resourcePath + '/resources/img/room_page/' + dtoObject.right.card.toLowerCase() + '.png">');
    }



    $("#desks #table" + dtoObject.id + " .leftSide").html(dtoObject.left.name + " " + dtoObject.left.card);
    $("#desks #table" + dtoObject.id + " .rightSide").html(dtoObject.right.name + " " + dtoObject.right.card);

}


var jsonStringShip = '{"type":"SHIP","name":"Expoir","time":1427902817041,"players":[\
{"name":"Yusya","state":"ONLINE","delet":false,"stars":3},\
{"name":"Dusya","state":"IN_DUEL","delet":false,"stars":2},\
{"name":"Tanya","state":"OFFLINE","delet":false,"stars":5},\
{"name":"Toby","state":"ONLINE","delet":false,"stars":3},\
{"name":"Miki","state":"ONLINE","delet":false,"stars":9}],\
"state":"Game","deck":{"Scissors":6,"Paper":4,"Bull":6,"Stone":3}}';

var jsonStringPlayer = '{"type":"PLAYER","name":"Tanya","deck":{"Scissors":6,"Stone":2},\
"whoChallenging":[{"name":"Yusya","state":null,"delet":false,"stars":-5},\
{"name":"Yanukovichus","state":null,"delet":false,"stars":null}],"iChallenged":\
[{"name":"Toby","state":null,"delet":false,"stars":null}]}';

var jsonStringTable = '{"type":"TABLE","id":1,"state":"IN_GAME","left":{"name":"Tanya","card":null},"right":{"name":"Miki","card":null}}';
var jsonStringTable2 = '{"type":"TABLE","id":0,"state":"EMPTY","left":{"name":"Tommy","card":null},"right":{"name":"Trace","card":null}}';
var jsonStringTable3 = '{"type":"TABLE","id":1,"state":"IN_GAME","left":{"name":"Tanya","card":"Stone"},"right":{"name":"Miki","card":"Scissors"}}';


// Start************************


function processDto(dtoObject) {

    console.log("======= processDto method ===========");
    console.log(dtoObject);
    switch (dtoObject.type) {


        case "SHIP":
            processDtoShip(dtoObject);
            break;
        case "PLAYER":
            processDtoPlayer(dtoObject);
            break;
        case "TABLE":
            processDtoTable(dtoObject);
            break;
        case "ERROR":
            break;
        case "MESSAGE":
            break;
    }
}

//--------------------------------------------------------------------------

function pause(n) {
    var today = new Date()
    var today2 = today
    while ((today2 - today) <= n) {
        today2 = new Date()
    }
}


/*
 sendAnswer = function(argument) {
 console.log("ANSWER");
 console.log(argument);
 }
 */


//});
//--------------------------------------------------------------------------


function kaijiBeginGame(endPoint, subscribePath, answerPath) {
    sockJS = new SockJS(endPoint);
    stompClient = Stomp.over(sockJS);

    stompClient.connect({}, function (frame) {
        stompClient.subscribe(subscribePath, function (msg) {//on income msg
            processDto(JSON.parse(msg.body));//code
        });

        sockJS.onclose = function () {//on disconnect
            alert('disconnected');
        };

        sendAnswer = function (msg) {
            stompClient.send(answerPath, {}, msg);
        }
    });
}

